package net.xdclass.online_xdclass.controller;

import net.xdclass.online_xdclass.model.entity.User;
import net.xdclass.online_xdclass.model.entity.request.LoginRequest;
import net.xdclass.online_xdclass.service.UserService;
import net.xdclass.online_xdclass.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RestController
@RequestMapping("api/v1/pri/user")
public class UserController {

    @Autowired
    private UserService userService;
//@RequestBody接收json格式
// 前端传进来的是json格式可以映射到Map里面
    @PostMapping("register")
    public JsonData register(@RequestBody Map<String,String> userInfo)  {

int rows=userService.save(userInfo);


        return rows ==1?JsonData.buildSuccess() : JsonData.buildError("登录失败");
    }
    @PostMapping("login")
    public JsonData login(@RequestBody LoginRequest loginRequest){
        String token  = userService.findByPhoneAndPwd(loginRequest.getPhone(),loginRequest.getPwd());
return token ==null? JsonData.buildError("登录失败账号密码错误"):JsonData.buildSuccess(token);
    }

    @GetMapping("find_by_token")
    public JsonData ByUserInfoToken(HttpServletRequest request){
        Integer userId=(Integer) request.getAttribute("user_id");
        if (userId==null){
            return JsonData.buildError("用户信息为空");

        }
        User user=userService.findByUserId(userId);
        return JsonData.buildSuccess(user);
    }
}
